package com.timepies.domain;

import static com.timepies.persistence.DatabaseStrings.FIELD_DATE;
import static com.timepies.persistence.DatabaseStrings.FIELD_SUBJECT;
import static com.timepies.persistence.DatabaseStrings.FIELD_TEXT;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.timepies.R;
import com.timepies.util.Intervallo;

public class TimepieAdapterDatabase extends CursorAdapter {

	static class ViewHolder {
		int idDate;
		int idOggetto;
		int idTesto;
		TextView txtDate;
		TextView txtOggetto;
		TextView txtTesto;
	}

	public TimepieAdapterDatabase(Context context, Cursor c, int flags) {
		super(context, c, flags);
	}

	@Override
	public View newView(final Context context, Cursor cursor, ViewGroup parent) {

		int color = Pie.randomColor(cursor.getPosition());

		View view = LayoutInflater.from(context).inflate(
				R.layout.activity_pie_elenco_riga, null);

		ViewHolder holder = new ViewHolder();
		holder.txtTesto = (TextView) view.findViewById(R.id.txt_testo);
		holder.txtOggetto = (TextView) view.findViewById(R.id.txt_oggetto);
		holder.txtDate = (TextView) view.findViewById(R.id.txt_date);

		holder.idTesto = cursor.getColumnIndexOrThrow(FIELD_SUBJECT);
		holder.idOggetto = cursor.getColumnIndexOrThrow(FIELD_TEXT);
		holder.idDate = cursor.getColumnIndexOrThrow(FIELD_DATE);

		view.setTag(holder);

		LinearLayout l = (LinearLayout) view.findViewById(R.id.color);
		l.setBackgroundColor(color);

		return view;
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		ViewHolder holder = (ViewHolder) view.getTag();
		String dateInString = cursor.getString(holder.idDate);
		holder.txtOggetto.setText(cursor.getString(holder.idOggetto));
		holder.txtTesto.setText(cursor.getString(holder.idTesto));
		holder.txtDate.setText(dateInString);

		TextView amg = (TextView) view.findViewById(R.id.anno_mese_giorno);
		amg.setText(Intervallo.printTxtElapsed(dateInString, false));

	}

}